package com.llsydn.beijingnews.menudetailpager;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.google.gson.Gson;
import com.llsydn.beijingnews.R;
import com.llsydn.beijingnews.base.BaseMenuDetailPager;
import com.llsydn.beijingnews.common.Constants;
import com.llsydn.beijingnews.domain.NewsBean;
import com.llsydn.beijingnews.domain.PhotoBean;
import com.llsydn.beijingnews.util.BitmapCacheUtils;
import com.llsydn.beijingnews.util.CacheUtils;
import com.llsydn.beijingnews.util.LogUtil;
import com.llsydn.beijingnews.util.NetCacheUtils;
import com.llsydn.beijingnews.volley.VolleyManager;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.List;

/**
 * @author lilinshen
 * @title 互动详情页面
 * @description 请填写相关描述
 * @date 2018/10/25 16:43
 */
public class InteracMenuDetailPager extends BaseMenuDetailPager {

    private final NewsBean.DataBean dataBean;
    @ViewInject(R.id.listview)
    private ListView listview;
    @ViewInject(R.id.gridview)
    private GridView gridview;
    private String url;
    private List<PhotoBean.DataBean.NewsBean> photos;
    private PhotosMenuAdapter adapter;
    // 图片三级缓存工具类
    private BitmapCacheUtils bitmapCacheUtils;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case NetCacheUtils.SUCESS://图片请求成功
                    int position = msg.arg1;
                    Bitmap bitmap = (Bitmap) msg.obj;
                    if (listview.isShown()) {
                        ImageView iv_icon = (ImageView) listview.findViewWithTag(position);
                        if (iv_icon != null && bitmap != null) {
                            iv_icon.setImageBitmap(bitmap);
                        }
                    }
                    if (gridview.isShown()) {
                        ImageView iv_icon = (ImageView) gridview.findViewWithTag(position);
                        if (iv_icon != null && bitmap != null) {
                            iv_icon.setImageBitmap(bitmap);
                        }
                    }
                    LogUtil.e("请求图片成功==" + position);
                    break;
                case NetCacheUtils.FAIL://图片请求失败
                    position = msg.arg1;
                    LogUtil.e("请求图片失败==" + position);
                    break;
            }
        }
    };

    public InteracMenuDetailPager(Context context, NewsBean.DataBean dataBean) {
        super(context);
        this.dataBean = dataBean;
        bitmapCacheUtils = new BitmapCacheUtils(handler, context);
    }

    @Override
    public View initView() {
        View view = View.inflate(context, R.layout.photos_menudetail_pager, null);
        x.view().inject(this, view);
        return view;
    }

    @Override
    public void initData() {
        super.initData();
        url = Constants.BASE_URL + dataBean.getUrl();
        String saveJson = CacheUtils.getString(context, url);
        if (!TextUtils.isEmpty(saveJson)) {
            processData(saveJson);
        }
        getDataFromWebServer();

    }

    /**
     * 使用xutils3联网请求
     */
    private void getDataFromWebServer() {
        RequestParams params = new RequestParams(url);
        // 发送http的get请求
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtil.e("使用xutils3联网请求成功==" + result);
                // 缓存数据
                CacheUtils.putString(context, url, result);
                // 处理数据
                processData(result);
                // 设置适配器
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                // LogUtil.e("使用xutils3联网请求失败==" + ex.getMessage());
                LogUtil.e("使用xutils3联网请求失败");
            }

            @Override
            public void onCancelled(CancelledException cex) {
                LogUtil.e("使用xutils3联网请求取消==" + cex.getMessage());
            }

            @Override
            public void onFinished() {
                LogUtil.e("使用xutils3联网请求完成==");
            }
        });
    }

    /**
     * 解析和显示数据
     *
     * @param saveJson
     */
    private void processData(String saveJson) {
        PhotoBean photoBean = new Gson().fromJson(saveJson, PhotoBean.class);
        photos = photoBean.getData().getNews();
        LogUtil.e("互动详情页面数据====" + new Gson().toJson(photos));
        // 设置适配器
        adapter = new PhotosMenuAdapter();
        listview.setAdapter(adapter);

    }


    class PhotosMenuAdapter extends BaseAdapter {
        private DisplayImageOptions options;

        public PhotosMenuAdapter() {
            options = new DisplayImageOptions.Builder()
                    .showImageOnLoading(R.drawable.home_scroll_default)
                    .showImageForEmptyUri(R.drawable.home_scroll_default)
                    .showImageOnFail(R.drawable.home_scroll_default)
                    .cacheInMemory(true)
                    .cacheOnDisk(true)
                    .considerExifParams(true)
                    .bitmapConfig(Bitmap.Config.RGB_565)
                    .displayer(new RoundedBitmapDisplayer(10))  // 设置矩形圆角
                    .build();
        }

        @Override
        public int getCount() {
            return photos.size();
        }

        @Override
        public Object getItem(int position) {
            return photos.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            PhotosMenuDetailPager.ViewHolder viewHolder = null;
            if (convertView == null) {
                convertView = View.inflate(context, R.layout.item_photos_menu, null);
                viewHolder = new PhotosMenuDetailPager.ViewHolder();
                viewHolder.iv_icon = convertView.findViewById(R.id.iv_icon);
                viewHolder.tv_title = convertView.findViewById(R.id.tv_title);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (PhotosMenuDetailPager.ViewHolder) convertView.getTag();
            }
            // 根据位置得到对应的数据
            PhotoBean.DataBean.NewsBean bean = photos.get(position);
            viewHolder.tv_title.setText(bean.getTitle());
            // 联网设置图片
            String imageUrl = Constants.BASE_URL + bean.getSmallimage();
            // 1.使用volley请求图片
            // loaderImager(viewHolder, imageUrl);
            // 使用自定义的三级缓存请求图片
            Bitmap bitmap = bitmapCacheUtils.getBitmap(imageUrl, position);
            if (bitmap != null) {
                viewHolder.iv_icon.setImageBitmap(bitmap);
            }
            // 2.使用picasso请求网络图片
            // Picasso.with(context)
            //         .load(imageUrl)
            //         .placeholder(R.drawable.home_scroll_default)
            //         .error(R.drawable.home_scroll_default)
            //         .into(viewHolder.iv_icon);

            // 3.使用glide请求网络图片（性能会更好点）
            // Glide.with(context)
            //         .load(imageUrl)
            //         .diskCacheStrategy(DiskCacheStrategy.ALL)
            //         .placeholder(R.drawable.home_scroll_default)
            //         .error(R.drawable.home_scroll_default)
            //         .into(viewHolder.iv_icon);

            // 4.使用imageloader加载图片
            com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage(imageUrl, viewHolder.iv_icon, options);
            return convertView;
        }
    }

    static class ViewHolder {
        ImageView iv_icon;
        TextView tv_title;
    }

    /**
     * 使用volley请求图片
     *
     * @param viewHolder
     * @param imageurl
     */
    private void loaderImager(final PhotosMenuDetailPager.ViewHolder viewHolder, String imageurl) {
        viewHolder.iv_icon.setTag(imageurl);
        //直接在这里请求会乱位置
        ImageLoader.ImageListener listener = new ImageLoader.ImageListener() {
            @Override
            public void onResponse(ImageLoader.ImageContainer imageContainer, boolean b) {
                if (imageContainer != null) {

                    if (viewHolder.iv_icon != null) {
                        if (imageContainer.getBitmap() != null) {
                            viewHolder.iv_icon.setImageBitmap(imageContainer.getBitmap());
                        } else {
                            viewHolder.iv_icon.setImageResource(R.drawable.home_scroll_default);
                        }
                    }
                }
            }

            @Override
            public void onErrorResponse(VolleyError volleyError) {
                //如果出错，则说明都不显示（简单处理），最好准备一张出错图片
                viewHolder.iv_icon.setImageResource(R.drawable.home_scroll_default);
            }
        };
        VolleyManager.getImageLoader().get(imageurl, listener);
    }

    private boolean isShowListView = true;

    /**
     * 调用图组对象的切换listview和grdiview
     *
     * @param ib_swich_list_grid
     */
    public void switchListAndGrid(ImageButton ib_swich_list_grid) {
        if (isShowListView) {
            isShowListView = false;
            // 显示girdview,隐藏listview
            gridview.setVisibility(View.VISIBLE);
            adapter = new PhotosMenuAdapter();
            gridview.setAdapter(adapter);
            listview.setVisibility(View.GONE);
            // 按钮显示listview
            ib_swich_list_grid.setImageResource(R.drawable.icon_pic_list_type);
        } else {
            isShowListView = true;
            // 显示listview,隐藏gridview
            gridview.setVisibility(View.GONE);
            adapter = new PhotosMenuAdapter();
            listview.setAdapter(adapter);
            listview.setVisibility(View.VISIBLE);

            // 按钮显示gridview
            ib_swich_list_grid.setImageResource(R.drawable.icon_pic_grid_type);
        }
    }
}